package Impor;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

import entity.BaseDao;
import entity.StuDao;
import entity.student;

public class StuDaoMySqlImpl extends BaseDao implements StuDao {

	@Override
	public int add(student s) {
		// 添加
		String sql = "insert into student (stuno,sname,gradeid ) values (?,?,?)";
		Object[] add = { s.getStuno(), s.getSname(), s.getGradeid() };
		int row = super.exeUpdate(sql, add);
		return row;
	}

	@Override
	public int update(student s) {
		// 更新
		String sql = "update student set gradeid =? where stuno =?";
		Object[] upda = { s.getGradeid(), s.getStuno() };
		int row = super.exeUpdate(sql, upda);
		return row;
	}

	@Override
	public int del(student s) {
		// 删除
		String sql = "delete from student where stuno = ?";
		Object[] del = { s.getStuno() };
		int row = super.exeUpdate(sql, del);
		return row;
	}

	@Override
	// 查询指定学号的学生信息
	public student get(int id) {
		String sql = "select * from student where stuno=?";
		student s = null;
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			con = getConnection();
			ps = con.prepareStatement(sql);
			ps.setInt(1, id); // 方法参数指定要查询的学生信息
			rs = ps.executeQuery();
			if (rs.next()) {
				s = new student();
				s.setStuno(id);
				s.setSname(rs.getString("sname"));// 查询结果集做参数，来修改学生类里面的数据
				s.setAddress(rs.getString("address"));
				s.setGradeid(rs.getInt("gradeid"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			closeAll(con, ps, rs);
		}
		return s;
	}

	// 添加学生考试分数记录
	public int addScore(int id, float score, int st_no, int sb_no) {
		String sql = "INSERT INTO examresult(id,score,st_id,sb_id) VALUES (?,?,?,?) ";
		Object[] arg = { id, score, st_no, sb_no };
		int row = super.exeUpdate(sql, arg);
		return row;
	}

	@Override
	public student login(int stuno, String pass) {
		// TODO Auto-generated method stub
		return null;
	}
	
	// 根据 页号，实现分页查询
	public java.util.List<student> find(int pageNo, int pageSize) {
		List<student> list = new ArrayList<student>();
		Connection con = super.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;
		student s = null;
		try {
			String sql = "select * from student order by stuno desc limit ?,?";
			ps = con.prepareStatement(sql);
			ps.setInt(1, (pageNo - 1) * pageSize);
			ps.setInt(2, pageSize);
			rs = ps.executeQuery();
			//读取返回的数据，添加到学生类中
			while (rs.next()) {
				s = new student();
				s.setSname(rs.getString("sname"));
				s.setStuno(rs.getInt("stuno"));
				s.setGradeid(rs.getInt("gradeid"));
				s.setQq(rs.getString("qq"));
				s.setSex(rs.getString("sex"));
				list.add(s);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			super.closeAll(con, ps, rs);
		}
			return list;
		}

}
